package com.music.muisc.controllers;

import com.music.muisc.dao.MusicRepository;
import com.music.muisc.dao.UnitRepository;
import com.music.muisc.entity.Music;
import com.music.muisc.entity.Unit;
import com.music.muisc.services.MusicService;
import com.music.muisc.services.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("musics")
public class MusicController {

    @Autowired
    MusicService musicService;

    @Autowired
    UnitService unitService;

    @GetMapping
    public String displayMusics(Model model){
        List<Music> musics = musicService.getAll();
        model.addAttribute("musics",musics);
        return "musics/list-musics";
    }
@GetMapping("/new")
    public String displayMusicForm(Model model){
    Music aMusic = new Music();//定义要传入的数据为新建的Music实例
    List<Unit> units = unitService.getAll();
    model.addAttribute("music",aMusic);
    model.addAttribute("allUnits", units);
    return "musics/new-music";

    }
    @PostMapping("/save")
    public String createMusic(Model model, @RequestParam List<Long> units, Music music){

    //处理保存到数据库的行为
        musicService.save(music);

        //使用重定位防止重复提交
        return "redirect:/musics";
    }


}
